package blog.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import blog.entity.Article;
import blog.entity.Comment;
import blog.mapper.CommentMapper;
import blog.service.ArticleService;
import blog.service.CommentService;
/**
 * 评论服务层
 * @author 江佳洋
 *
 */
@Service
public class CommentServiceImpl implements CommentService{
	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private ArticleService articleService;
	
	/**
	 * 查询n条评论信息
	 */
	public List<Comment> listRecentComment(Integer n) {
		List<Comment> listRecentComment = commentMapper.listRecentComment(n);
		for(Comment c:listRecentComment) {
			Article articleById = articleService.getArticleById(c.getCommentArticleId());
			c.setArticle(articleById);
		}
		return listRecentComment;
	}

	/**
	 * 查询所有的评论
	 * @return
	 */
	public PageInfo<Comment>  findAllPageComment(Integer pageIndex,Integer pageSize) {
		PageHelper.startPage(pageIndex,pageSize);
		List<Comment> findAllComment = commentMapper.findAllComment();
		
		PageInfo<Comment> page = new PageInfo<Comment>(findAllComment);
		for(Comment com:page.getList()) {
			Article articleById = articleService.getArticleById(com.getCommentArticleId());
			com.setArticle(articleById);
		}
		return page;
	}

	/**
	 * 根据id查询评论信息
	 * @param commentId
	 * @return
	 */
	public Comment getCommentById(Integer commentId) {
		return commentMapper.getCommentById(commentId);
	}

	/**
	 * 添加评论
	 * @param comment
	 */
	public void addComment(Comment comment) {
		commentMapper.addComment(comment);
		Article article = articleService.getArticleById(comment.getCommentArticleId());
		article.setArticleCommentCount(article.getArticleCommentCount()+1);
		articleService.updateArticle(article);
	}

	/**
	 * 删除评论
	 * @param commentId
	 */
	public void deleteComment(Integer commentId) {
		Comment comment = commentMapper.getCommentById(commentId);
		Article article = articleService.getArticleById(comment.getCommentArticleId());
		article.setArticleCommentCount(article.getArticleCommentCount()-1);
		articleService.updateArticle(article);
		commentMapper.deleteComment(commentId);
		
	}

}
